//
//  NetworkViewController.swift
//  AKTest
//
//  Created by ZDST2018 on 2021/8/25.
//

import UIKit
import Alamofire
import RxDataSources
class NetworkViewController: UIViewController {
    
    @IBOutlet weak var searchTF: UITextField!
    @IBOutlet weak var porjectList: UITableView!
    lazy var bag = DisposeBag.init()
    var modelArray: Array<repositoriesModel> = []
    
    typealias sectionTableModle = SectionModel<String, repositoriesModel>
    lazy var dataSource = RxTableViewSectionedReloadDataSource<sectionTableModle>.init { model, tabV, index, item in
        let cell: GitHubCell = tabV.dequeueReusableCell(withIdentifier: "cellID") as! GitHubCell
        cell.name.text = item.name
        
        return cell
    } titleForHeaderInSection: { model, index in
    
        let m =  model.sectionModels[index]
        
        
        let headV : GitHubHeadView = self.porjectList.dequeueReusableHeaderFooterView(withIdentifier: "headID") as! GitHubHeadView
        headV.rightLab.text = m.model
        return m.model
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //一个section的写法
        //        porjectList.register(UINib.init(nibName: "GitHubCell", bundle: nil), forCellReuseIdentifier: "cellID")
        //        searchTF.rx.text.throttle(.milliseconds(2000), scheduler: MainScheduler.init()).filter({ (text: String?) -> Bool in
        //            if let str = text, str.count < 3{
        //                return false
        //            }
        //            return true
        //        }).flatMap({[weak self] (str : String?) in
        //            self!.network(repositoryName: str!)
        //
        //        }).bind(to: porjectList.rx.items(cellIdentifier: "cellID", cellType: GitHubCell.self)){ index, model, cell in
        //            cell.name.text = model.name
        //
        //        }.disposed(by: bag)
        
        
        //多个section的写法
        porjectList.delegate = self
        porjectList.register(UINib.init(nibName: "GitHubCell", bundle: nil), forCellReuseIdentifier: "cellID")
        porjectList.register(UINib.init(nibName: "GitHubHeadView", bundle: nil), forHeaderFooterViewReuseIdentifier: "headID")
        searchTF.rx.text.throttle(.milliseconds(2000), scheduler: MainScheduler.init()).filter({ (text: String?) -> Bool in
            if let str = text, str.count < 3{
                return false
            }
            return true
        }).flatMap({[weak self] (str : String?) in
            self!.network(repositoryName: str!)
        }).subscribe { eve in
            switch eve{
            case .next(let arr):
                self.porjectList.dataSource = nil
                print(arr)
                Observable.just(self.createGithubSectionModel(repoInfo: arr)).bind(to: self.porjectList.rx.items(dataSource: self.dataSource)).disposed(by: self.bag)
                
            default:
                break
            }
            
        }.disposed(by: bag)
        porjectList.rxDidSelectRowAtIndexPath.subscribe { eve in
            switch eve {
            case .next(let (tab, indexPath)):
                tab.deselectRow(at: indexPath as IndexPath, animated: true)
            default:
                break
            }
        }.disposed(by: bag)
        
        porjectList.rxViewForHeaderInSection.subscribe { eve in
           
        }.disposed(by: bag)
    }
    
}

extension NetworkViewController: UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("---***----")
    }
}

extension NetworkViewController{
    
    
    func createGithubSectionModel(repoInfo:[repositoriesModel]) -> [sectionTableModle] {
        var ret: [sectionTableModle] = []
        var items : [repositoriesModel] = []
        if repoInfo.count <= 10 {
            ret.append(sectionTableModle.init(model: "Top 1 - 10", items: repoInfo))
        }else{
            for  i in 1...repoInfo.count {
                items.append(repoInfo[i-1])
                let isSectionBreak = i / 10 != 0 && i % 10 == 0
                
                if isSectionBreak {
                    ret.append(sectionTableModle.init(model: "Top\(i-9)-\(i)", items: items))
                    items = []
                }
                
            }
        }
        return ret
    }
    
    func network(repositoryName: String) -> Observable<Array<repositoriesModel>> {
        
        return Observable.create { (obs : AnyObserver<Array<repositoriesModel>>) -> Disposable in
            let url = "https://api.github.com/search/repositories"
            AlamoFireTool.get(url: url, parameters: ["q":repositoryName]).responseJSON { (dataRes: DataResponse<Any>) in
                switch dataRes.result {
                case .success(let json):
                    let dict = json as? [String: Any]
                    let total_count = dict?["total_count"] as! Int
                    
                    guard total_count != 0 else {
                        print("没有这个框架")
                        return
                    }
                    let arr = dict?["items"] as? [Dictionary<String, Any>]
                    obs.onNext(arr?.kj.modelArray(repositoriesModel.self) ?? [])
                case .failure(let error):
                    print(error)
                }
            }
            
            return Disposables.create()
        }
    }
}


struct repositoriesModel: Convertible, CustomStringConvertible {
    var avatar_url: String = ""
    var name: String = ""
    init() {}
    func kj_modelKey(from property: Property) -> ModelPropertyKey {
        switch property.name {
        case "avatar_url":
            return "owner.avatar_url"
        default:
            return property.name
        }
    }
    
    var description: String{
        get{
            self.kj.JSONString()
        }
    }
}
